<template>
  <div class="schepost">
    <label style="height: 30px; line-height: 30px; display: inline-block;">出港地点：</label>
    <!--a-input placeholder="请输入启始出港地点" v-model:value="schepostText" ></a-input>
    <JSelectInput-- v-model:value="schepost.value" placeholder="请输入启始出港地点"
      :options="schepostOptions"
      @change="" class="w-150px"
    ></JSelectInput>
    <a-select placeholder="请输入启始出港地点" class="w-200px"
              v-model:value="schepost.value"
              :options="schepostOptions"
              :autoClearSearchValue="true"
              :showSearch="true"
              :filter-option="false"
              :not-found-content="null"
              @change="handleSchepostChange"
              @search="handleSchepostBlur"
    /-->
    <AutoComplete
      v-model:value="schepost.value"
      :options="schepostOptions"
      @select="handleSchepostSelect"
      @search="handleSchepostSearch"
      style="width: 180px"
      placeholder="请输入启始出港地点"
    />
    <span class="p-1" style="display: inline-block; width: 426px"> 已有排 <span class="font-600 text-red-600">{{ MOCK_DATA.length || 0 }}</span> 期 </span>
    <a-button size="small" color="success" @click="saveSchepost()" v-show="!schepost.id" style="padding: 0 10px; margin-left: 8px">添加</a-button>
    <a-button size="small" color="warning" @click="saveSchepost()" v-show="schepost.id" style="padding: 0 10px; margin-left: 8px">修改</a-button>
    <a-button size="small" color="error" @click="delSchepost()" :disabled="!schepost.id" style="padding: 0 10px; margin-left: 8px" >删除</a-button>
  </div>
  <div class="container" style="width:800px; min-height:675px; margin-top: 2px"></div>
</template>

<script>
/**
 * 文件: cmsSchedule.js
 * 功能:  排期价格
 * 作者:  qindl
 * 时间:  2021-05-26
 */
import "/@/components/jquery/jquery-1.8.3"
import * as jquery from "jquery";
let $ = jquery;
if (window.jQuery) {
  $ = window.jQuery;
}else{
  window.jQuery = $;
}
import { ref, onUnmounted, unref, nextTick, watch } from 'vue';
import "/@/components/CalendarPrice/src/js/polyfill.min.js"
import "/@/components/CalendarPrice/src/js/calendar-price-jquery.js"
import "/@/components/CalendarPrice/src/css/calendar-price.min.css"
import { propTypes } from "/@/utils/propTypes";
import { useMessage } from "/@/hooks/web/useMessage";
import {
  cmsSchepostList,
  cmsSchepostAdd,
  cmsSchepostDel,
  cmsScheduleList,
  cmsScheduleSave
} from "/@/views/weixin/article/artticle.api";
import { createMockData, randomEndDate, calendarConfig, showConfig, styleConfig } from "./mock.data"
import JSelectInput from "/@/components/Form/src/jeecg/components/JSelectInput.vue";
import { AutoComplete } from 'ant-design-vue';
export default {
  components: { JSelectInput, AutoComplete },
  props: {
    articleId: propTypes.string.def(''),
  },
  watch: {
    // articleId: {
    //   handler(newValue, oldValue) {
    //     if (newValue === oldValue) return;
    //     this.$nextTick(() => {
    //       this.init()
    //     });
    //   },
    //   immediate: false,
    //   deep: true
    // }
    articleId (val) {
      //console.info("articleId@@@@@@@", !val)
      if (!val) return;
      this.$nextTick(() => {
        this.init()
      });
    },
  },
  mounted() {
    ///if(this.articleId) this.init()
  },
  data() {
    return {
      MOCK_DATA: {},
      zxCalendar: {},
      schepostText: "",
      schepost: {},
      schepostOptions: [],
      startDay: '',
      endDay: '',
    }
  },
  methods: {
    async init() {
      //价格排期 -- 界面
      await this.initCmsSchedule();
      //价格排期 -- 操作
      await this.handleCmsSchedule();
      //出港地点 -- 数据
      await this.initSchepost();
    },

    //----开始---出港地点------出港地点--------------------------------------
    initSchepost() {
      let params = { articleId: this.articleId };
      cmsSchepostList(params).then((res) => {
        //console.info("initSchepost@@@@1", params)
        this.schepostOptions = res || []
        if (res.length > 0 && !this.schepost.value) {
          //1、打开界面默认显示第一项目
          Object.assign(this.schepost, res[0])
        } else {
          //2、添加操作后显示
          var vl = this.schepost.value
          if (vl) {
           this.updateSchepost(vl)
          }
        }
      }).finally(() => {
        //价格排期 -- 数据
        this.loadCmsSchedule();
      });
    },

    saveSchepost(oper) {
      var id   = this.schepost.id
      var text = this.schepost.value
      if (!text) {
        alert("请输入出港地点名称！");
        return false;
      }
      var articleId = this.articleId
      if (!articleId) {
        alert("文章编号不能为空！");
        return false;
      }
      let data = {
        'articleId': (articleId || null)
        , 'id': id
        , 'text': text
      }
      cmsSchepostAdd(data).then((res) => {
        if(res && res['success']) {
          this.initSchepost();
          useMessage().createMessage.success(res['message']);
        } else {
          useMessage().createMessage.warning(res['message']);
        }
      })
    },

    delSchepost() {
      let id = this.schepost.id
      if (!id) {
        useMessage().createMessage.warning("请选择出港地点！");
        return false
      }
      let data = {
        'id': id
      }
      // let data = {
      //   'id': '11111'
      // }
      cmsSchepostDel(data, () => {
        Object.assign(this.schepost, {id:'', value:''})
        //价格排期 -- 数据
        this.initSchepost();
      })
    },

    updateSchepost(val) {
      let sel = this.schepostOptions.filter((item) => item.value === val)
      Object.assign(this.schepost, sel[0])
    },

    handleSchepostSelect(val) {
      this.updateSchepost(val)
      this.initSchepost()
      //console.info("handleSchepostSelect@@@@", this.schepost)
      //价格排期 -- 数据
    },

    handleSchepostSearch(val) {
      if (val) {
        Object.assign(this.schepost, {value: val})
      } else {
        Object.assign(this.schepost, {id:'', value:''})
      }
      //console.info("handleSchepostSearch@@@@", val, this.schepost)
    },

    //----结束---出港地点------出港地点--------------------------------------

    //打开排期价格窗口 2021-05-25 qindl
    loadCmsSchedule() {
      let params = { articleId: this.articleId, schepostId: this.schepost.id };
      cmsScheduleList(params).then((res) => {
        this.MOCK_DATA = [];
        if(res && res.length > 0) {
          //var dat = ["2018-06-01", "2018-07-01", "2018-07-02", "2018-07-10"]
          let result = []
          for(var i = 0; i < res.length; i++) {
            result.push({
              id: res[i].id,
              date: res[i].tourDate,
              price: res[i].price,
              priceChild: res[i].priceChild,
              priceSettlement: res[i].priceVip,
              member: res[i].priceRoom,
              seat: res[i].seat,
            });
          }
          this.MOCK_DATA = result;
        }
      }).finally(() => {
        //价格排期 -- 数据
        this.initCmsSchedule();
      });
      //console.info("cmsScheduleList@@@@2222", params, this.MOCK_DATA)
    },

    initCmsSchedule() {
      // 生成模拟数据
      //let MOCK_DATA = createMockData();
      let MOCK_DATA = this.MOCK_DATA;

      // 日历设置表单字段配置
      // key 字段名
      // name 表单label
      // value 默认值
      // placeholder input[placeholder]

      // 初始化日历
      this.zxCalendar = $.CalendarPrice({
        el: '.container',
        // startDate: '2017-08-02',
        endDate: randomEndDate(),
        data: MOCK_DATA,
        // 配置需要设置的字段名称
        config: calendarConfig,
        // 配置在日历中要显示的字段
        show: showConfig,
        // 自定义颜色
        style: styleConfig
      });

      //console.info("initCmsSchedule@@3333", MOCK_DATA)
    },

    handleCmsSchedule() {
      //初始化出港地点
      let me = this
      //console.info("handleCmsSchedule@@44444")
      // 监听设置表单提交
      // 将阻止默认流程执行
      // 继续执行默认流程，请执行参数next()
      me.zxCalendar.$on('submit-form', function (data, next) {
        // data 设置的数据
        me.log('$(submit-form)表单数据 ================')
        me.log(data)

        // 此处可以验证表单
        // 验证表单逻辑....
        var price = $("input[name=price]").val();
        var priceChild = $("input[name=priceChild]").val();
        var priceSettlement = $("input[name=priceSettlement]").val();
        if(!price) {
          alert('成人价不能为空，请输入');
          $("input[name=price]").focus();
          return false;
        }
        if(typeof price !== 'number1' && isNaN(price)) {
          alert('成人价请输入数字');
          $("input[name=price]").focus();
          return false;
        }
        if(!priceChild) {
          alert('儿童价不能为空，请输入');
          $("input[name=price]").focus();
          return false;
        }
        if(typeof priceChild !== 'number1' && isNaN(priceChild)) {
          alert('儿童价请输入数字');
          $("input[name=priceChild]").focus();
          return false;
        }
        if(!priceSettlement) {
          alert('同行返不能为空，请输入');
          $("input[name=priceSettlement]").focus();
          return false;
        }
        if(typeof priceSettlement !== 'number1' && isNaN(priceSettlement)) {
          alert('同行返请输入数字');
          $("input[name=priceSettlement]").focus();
          return false;
        }

        var times = data.weeks.join() + data.days.join();
        if (times.length == 0) {
          alert('请选择排期');
          return false;
        }

        me.saveSchedule(data)
        // 继续执行下一步
        next();
      })

      // 执行过程中错误回调
      me.zxCalendar.$on('error', function (err) {
        // 执行中的错误提示
        //console.error('$on(error)Error:')
        me.log(err)
        alert(err.msg);
      })

      // 切换月份
      me.zxCalendar.$on('month-change', function (data) {
        me.log('$on(month-change) 数据：');
        me.log(data);
      })

      // 点击有效的某一天通知
      me.zxCalendar.$on('valid-day', function (day, data, next) {
        me.log('$on(valid-day)当前点击的(有效)日期为: ' + day + ', 数据：');
        me.log(data);
        $('div.capricorncd-date-detailed-settings:not(:last)').remove();
        // 继续执行默认流程
        next();
      })

      // 设置数据变化
      me.zxCalendar.$on('setup-value-change', function (data) {
        me.log('$on(setup-value-change)设置窗口被修改数据....');
        me.log(data);
        // 取消设置
        // 这里可以触发关闭设置窗口
      })

      // 点击重置按钮回调
      me.zxCalendar.$on('reset', function () {
        me.log('$on(reset)数据重置成功！');
      })

      // 点击确定按钮回调，返回当前设置数据
      me.zxCalendar.$on('confirm', function (data) {
        me.log('$on(confirm)点击确定按钮通知！');
        me.log(data);
      })

      // 点击取消按钮回调
      me.zxCalendar.$on('cancel', function () {
        me.log('$on(cancel)取消设置 ....');
        // 取消设置
        // 这里可以触发关闭设置窗口
      })
      me.zxCalendar.$on('setup-close', function () {
        me.log('$on(setup-close)取消设置 ....');
        // 取消设置
        // 这里可以触发关闭设置窗口
      })
    },

    /**
     * 添加排期价格信息
     */
    saveSchedule : function (schedule) {
      var me  = this;
      var data = {
        'articleId': this.articleId || ''
        , 'schepostId': this.schepost.id || '' //2021-05-25 qindl
        , 'startDay': schedule.startDay
        , 'endDay': schedule.endDay
        , 'weeks': schedule.weeks.join()
        , 'days': schedule.days.join()
        , 'price': schedule.formData.price
        , 'priceChild': schedule.formData.priceChild
        , 'priceVip': schedule.formData.priceSettlement
        , 'priceRoom': schedule.formData.member
        , 'seat': schedule.formData.seat
      }
      cmsScheduleSave(data).then((res) => {
        //console.info("cmsScheduleSave@@@@", res)
        if(res && res['success']) {
          me.loadCmsSchedule();
          useMessage().createMessage.success('日期价格保存功能！');
        } else {
          useMessage().createMessage.warning(res['message']);
        }
      });
    },

    //日志
    log(s) {
      //console.log(s)
    },

  }
};
</script>
<style lang="less">
.calendar-table-wrapper table tbody tr td:first-child{
  border-left: 1px solid #eee;
}
.calendar-table-wrapper table thead th {
  font: bold 16px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
  color: #4f6b72;
  border-right: 1px solid #C1DAD7;
  border-bottom: 1px solid #C1DAD7;
  border-top: 1px solid #C1DAD7;
  letter-spacing: 2px;
  text-transform: uppercase;
  text-align: center;
  padding: 6px 6px 6px 12px;
  background: #CAE8EA no-repeat;
}
</style>
